<?php

declare(strict_types=1);

namespace App\Job;

use App\Model\PointPosition;
use Hyperf\AsyncQueue\Job;

class PositionExportJob extends Job
{
    public $params;

    protected $maxAttempts = 2;

    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        $header_data=[
            'ID',
            '点位名称',
            '所属分类',
            '所属区县',
            '责任单位',
        ];
        $file = $this->params['file_url'];
        $folder = BASE_PATH.'/public'.$file;
        $fp = fopen($folder,'w+');
        if (!empty($header_data)) {
            foreach ($header_data as $key => $value) {
                $header_data[$key] = iconv('utf-8', 'GBK', $value);
            }
            fputcsv($fp, $header_data);
        }
        $query = PointPosition::query()->orderBy('id','desc')->with(['mainunit','category','district']);
        $query_count = clone $query;
        $all = $query_count->count('id');
        $start_count=0;
        $query->chunk(300,function($positions) use($fp,$all,&$start_count){
            foreach ($positions as $position){
                //$row[0] = $user->mobile.' ';
                $row[0] = $position->id.' ';
                $row[1] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',$position->name);
                $row[2] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',object_get($position,'category.name','暂无'));
                $row[3] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',object_get($position,'district.name','暂无'));
                $row[4] = iconv('utf-8', 'GBK//TRANSLIT//IGNORE',object_get($position,'mainunit.name','暂无'));
                fputcsv($fp,$row);
            }
            $start_count+=300;
            $progress = $start_count>=$all?1:sprintf('%.2f',$start_count/$all);
            cache()->set('export_'.$this->params['hash_id'],$progress*100);

        });
    }
}
